package com.jsmtr.rms.entity;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;

/**
 * @author wyh
 */
public class ResponseBuilder {
    private Integer status = SUCCESS;
    private String msg = SUCCESS_STR;
    private String data = null;
    private Integer curPage = null;
    private Integer total = null;
    public final static int SUCCESS = 1;
    public final static int ERROR = 0;
    public final static String SUCCESS_STR = "正常";
    public final static String ERROR_STR = "异常";

    public ResponseBuilder() {
    }

    public ResponseBuilder setStatus(int status) {
        this.status = status;
        return this;
    }

    public ResponseBuilder setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public ResponseBuilder setData(String data) {
        this.data = data;
        return this;
    }

    public ResponseBuilder setPage(int curPage, int total) {
        this.curPage = curPage;
        this.total = total;
        return this;
    }

    public ResponseBuilder removePage() {
        this.curPage = null;
        this.total = null;
        return this;
    }

    public String build() {
        JSONObject responseJson = new JSONObject();
        responseJson.put("status", this.status);
        responseJson.put("msg", this.msg);
        responseJson.put("data", this.data);
        if (this.curPage != null && this.total != null) {
            JSONObject page = new JSONObject();
            page.put("curPage", this.curPage);
            page.put("total", this.total);
            responseJson.put("page", page);
        }
        return responseJson.toString();
    }

    public static void simpleResponse(boolean success, HttpServletResponse response) {
        try {
            ResponseBuilder builder = new ResponseBuilder();
            if (!success) {
                builder.setStatus(ResponseBuilder.ERROR);
                builder.setMsg(ResponseBuilder.ERROR_STR);
            }

            response.getWriter().write(builder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

